package com.zenithmind.mall.pojo.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.zenithmind.common.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 商品库存实体 - 遵循单一职责原则，专门管理库存信息
 * 
 * @author ZenithMind Team
 * @since 2025-07-03
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("mall_product_stock")
public class ProductStock extends BaseEntity {

    /**
     * 商品ID
     */
    private String productId;

    /**
     * 库存数量
     */
    private Integer stock;

    /**
     * 预警库存
     */
    private Integer lowStock;

    /**
     * 锁定库存（待支付订单占用的库存）
     */
    private Integer lockedStock;

    /**
     * 版本号（用于乐观锁）
     */
    private Integer version;

    // 业务方法

    /**
     * 检查库存是否充足
     */
    public boolean hasEnoughStock(Integer quantity) {
        if (quantity == null || quantity <= 0) {
            return false;
        }
        return getAvailableStock() >= quantity;
    }

    /**
     * 获取可用库存（总库存 - 锁定库存）
     */
    public Integer getAvailableStock() {
        int totalStock = this.stock != null ? this.stock : 0;
        int locked = this.lockedStock != null ? this.lockedStock : 0;
        return Math.max(0, totalStock - locked);
    }

    /**
     * 检查是否需要库存预警
     */
    public boolean needsStockAlert() {
        if (lowStock == null || lowStock <= 0) {
            return false;
        }
        return getAvailableStock() <= lowStock;
    }

    /**
     * 锁定库存
     */
    public boolean lockStock(Integer quantity) {
        if (!hasEnoughStock(quantity)) {
            return false;
        }
        this.lockedStock = (this.lockedStock != null ? this.lockedStock : 0) + quantity;
        return true;
    }

    /**
     * 释放锁定库存
     */
    public void unlockStock(Integer quantity) {
        if (quantity != null && quantity > 0) {
            this.lockedStock = Math.max(0, 
                (this.lockedStock != null ? this.lockedStock : 0) - quantity);
        }
    }

    /**
     * 扣减库存（实际出库）
     */
    public boolean decreaseStock(Integer quantity) {
        if (quantity == null || quantity <= 0) {
            return false;
        }
        
        int totalStock = this.stock != null ? this.stock : 0;
        if (totalStock < quantity) {
            return false;
        }
        
        this.stock = totalStock - quantity;
        // 同时释放对应的锁定库存
        unlockStock(quantity);
        return true;
    }

    /**
     * 增加库存（入库）
     */
    public void increaseStock(Integer quantity) {
        if (quantity != null && quantity > 0) {
            this.stock = (this.stock != null ? this.stock : 0) + quantity;
        }
    }

    /**
     * 检查库存数据是否有效
     */
    public boolean isValid() {
        return productId != null && !productId.trim().isEmpty() &&
               stock != null && stock >= 0 &&
               lockedStock != null && lockedStock >= 0 &&
               (lowStock == null || lowStock >= 0);
    }
}
